package web.servlet;

import entity.PageResult;
import entity.User;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.Converter;
import org.apache.commons.beanutils.converters.DateConverter;
import service.UserService;
import service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.Map;

@WebServlet("/user")
public class UserServlet extends BaseServlet{

    private UserService userService = new UserServiceImpl();

    private void findPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取分页参数
        String pageNumStr = req.getParameter("pageNum");
        String sizeStr = req.getParameter("size");

        //健壮性的保障
        int pageNum = 1;
        int size = 3;

        try {
            pageNum = Integer.parseInt(pageNumStr);
        }catch (Exception e){}
        try {
            size = Integer.parseInt(sizeStr);
        }catch (Exception e){}

        //执行分页查询业务
        PageResult<User> pageResult = userService.page(pageNum,size);

        //将数据写回到前端页面
        write2HTML(pageResult,resp);
    }

    private void findOne(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取id
        String idStr = req.getParameter("id");
        int id = Integer.parseInt(idStr);

        //调用service
        User user = userService.findOne(id);

        write2HTML(user,resp);
    }

    private void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, InvocationTargetException, IllegalAccessException {
        //接收参数
        Map<String, String[]> map = req.getParameterMap();
        //封装数据到User对象
        User user = new User();
        /*
            BeanUtils内部在封装日期数据时，默认支持 yyyy/MM/dd的日期字符串到Date对象的封装
            现在前端页面传递过来的日期格式是：yyyy-MM-dd,BeanUtils默认是不支持这种转换，所以抛异常了
                ConversionException: DateConverter does not support default String to 'Date' conversion

            解决问题方式：
                ① 页面修改成yyyy/MM/dd传递
                ② 在后台做一个格式兼容转换（采纳）
         */

        DateConverter converter = new DateConverter();
        converter.setPattern("yyyy-MM-dd");
        ConvertUtils.register(converter, Date.class);

        BeanUtils.copyProperties(user,map);

        //System.out.println(user);
        int count = userService.update(user);
        if (count > 0){
            //成功
            resp.getWriter().write("true");
        }else{
            //失败
            resp.getWriter().write("false");
        }
    }
}
